import { _decorator, Component, Label, Node, RichText, Sprite, SpriteFrame } from 'cc';

import { Core } from '../Core/Core';
import { EItemAffix, EItemType } from '../Item/Item';
import { ResourceManager } from '../Core/ResourceManager';
import { PicPath } from '../Config/ResourceConfig';
import { SkillConfig } from '../Config/SkillConfig';
import { EEvent, ESkill } from '../Config/Enum';
import { Skill } from './Skill';
const { ccclass, property } = _decorator;

@ccclass('SkillDetail')
export class SkillDetail extends Component {

    ndBG
    spIcon: Sprite
    //path: string
    //affixes:EItemAffix[] = [];
    //itemType
    lbDesc: RichText = null!;
    skillName: string = "";
    lbSkillName: Label = null!; // 武学名称标签
    lbLevel: Label = null!; // 武学等级标签
    lbSkillPoint: Label = null!; // 武学点标签

    protected onLoad(): void {
        this.ndBG = this.node.getChildByName("BG");
        this.spIcon = this.node.getChildByName("Board").getChildByName("Icon").getComponent(Sprite);
        this.lbDesc = this.node.getChildByName("Board").getChildByName("Desc").getComponent(RichText);
        this.lbSkillName = this.node.getChildByName("Board").getChildByName("SkillName").getComponent(Label);
        this.lbLevel = this.node.getChildByName("Board").getChildByName("Level").getComponent(Label); // 武学等级标签
        this.lbSkillPoint = this.node.getChildByName("Board").getChildByName("SkillPoint").getComponent(Label); // 武学点标签
        //this.itemType = Core.Instance.currentItem.itemType

    }

    protected onEnable(): void {

        // 获取当前武学实例
        const skill = Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill);
        // 获取武学配置
        const rawDesc = SkillConfig[Core.Instance.currentSkill].desc2 || "无描述";
        this.lbDesc.string = this.formatDescription(rawDesc, skill);


        // Core.Instance.currentSkill = (Core.Instance.currentPlayer + this.node.name ) as ESkill; // 假设节点名称是武学名称的一部分
        //console.log("321当前武学:", Core.Instance.currentSkill, "玩家类型:", Core.Instance.currentPlayer);


        this.lbSkillName.string = SkillConfig[Core.Instance.currentSkill].name || "无武学名称"; // 获取武学名称
        this.lbLevel.string = "等级:  " + skill.level; // 获取武学等级
        this.lbSkillPoint.string = "武学点: " + Core.Instance.players.get(Core.Instance.currentPlayer).skillPoints; // 获取武学点数

        // 展示DESC
        // this.lbDesc.string = SkillConfig[Core.Instance.currentSkill].desc2 || "无描述";


        // console.log("Core.Instance.currentPlayer in equipment detail", Core.Instance.currentPlayer);
        
        // 展示武学图标
        //this.spIcon.spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+'Icon'])  //ResourceManager.Instance.getRes<SpriteFrame>(PicPath[player+'Skill'+i+'Icon'])
        this.spIcon.spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+'Icon'])
        // ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[Core.Instance.currentSkill+"Icon"])
        // .then((spriteFrame) => {
        //     this.spIcon.spriteFrame = spriteFrame;
        // })
        // .catch((error) => {
        //     console.error("加载武学图标失败:", error);
        // });
        
        //展示三个符文


        // 事件
        this.ndBG.on(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        // 监听事件
        Core.Instance.event.on(EEvent.SkillUpgrade, this.onSkillUpgrade, this)        


    }

    protected onDisable(): void {
        this.ndBG.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        // 监听事件
        Core.Instance.event.off(EEvent.SkillUpgrade, this.onSkillUpgrade, this)     
        
    }

    start() {



        


    }

    update(deltaTime: number) {
        
    }

//   // 新增：格式化描述的方法
//   private formatDescription(template: string, skillData: any): string {
//     return template.replace(/{(\w+)}/g, (match, property) => {
//       const value = skillData[property];
//       if (value === undefined) return match;
      
//       const formatter = this.propertyFormatters[property] || ((v) => v.toString());
//       return formatter(value);
//     });
//   }


  // 修改 formatDescription 方法
private formatDescription(template: string, skillData: any): string {
    return template.replace(/{(\w+)}/g, (match, property) => {
        const value = skillData[property];
        if (value === undefined) return match;
        
        const formatter = this.propertyFormatters[property] || ((v) => v.toString());
        const formattedValue = formatter(value);
        
        // 所有数值都用黄色显示
        return `<color=#FFFF00>${formattedValue}</color>`;
    });
}

      // 添加属性格式化映射
  private propertyFormatters: Record<string, (value: any) => string> = {
    ap: (v) => Math.round(v).toString(),
    effectChance: (v) => Math.round(v * 100).toString(),
    // 可以继续添加其他属性的格式化方法
  };

    onButtonCloseWindow() {
        console.log("点击了BG");
        // 关闭物品详情
        this.node.active = false;

        Core.Instance.save(); // 保存数据

    }

    onBtnUpgrade() {

        let playerData = Core.Instance.players.get(Core.Instance.currentPlayer);
        let skillName = Core.Instance.currentSkill as ESkill; // 假设节点名称是武学名称的一部分
        //console.log("321当前武学名称:", skillName, "玩家数据:", playerData);
        let skill = playerData.skillData.skills.get(skillName);
        console.log("点击了升级按钮");

        // 检查武学是否可以升级
        if (playerData.skillPoints <= 0) {
            console.error("武学点不足，无法升级武学");
            return;
        }


        // 检查武学是否达到最大等级
        //console.log("321当前武学等级:", skill.level, "最大武学等级:", skill.maxLevel);
        if (skill.level >= skill.maxLevel) {
            console.error("武学已达到最大等级，无法升级");
            return;
        }

        playerData.skillPoints -= 1; // 扣除一个武学点
        //console.log("321当前武学点:", playerData.skillPoints);
        //console.log("321当前武学等级:", skill.level)

        // 这里可以添加升级武学的逻辑
        playerData.skillData.upgradeSkill(skillName);
        //console.log("321升级后的武学数据:", playerData.skillData.skills.get(skillName));


        //Core.Instance.event.emit(EEvent.PlayerDataChange) // 通知其他组件更新武学点显示
        

    }

    onSkillUpgrade(){
        // 当武学升级时，更新武学等级显示
        //console.log("321onSkillUpgrade in SkillDetail:", Core.Instance.currentSkill);
        const skill = Core.Instance.players.get(Core.Instance.currentPlayer).skillData.skills.get(Core.Instance.currentSkill as ESkill);
        //console.log("321onSkillUpgrade in SkillDetail: 当前武学:", skill);
        if (skill) {
            this.lbLevel.string = "等级:  " + skill.level; // 更新武学等级标签
            this.lbSkillPoint.string = "武学点: " + Core.Instance.players.get(Core.Instance.currentPlayer).skillPoints; // 更新武学点标签
            // 更新Desc
            const rawDesc = SkillConfig[Core.Instance.currentSkill].desc2 || "无描述";
            this.lbDesc.string = this.formatDescription(rawDesc, skill);
            //console.log("321武学升级，当前武学等级:", skill.level);
        } else {
            //console.error("321武学不存在:", Core.Instance.currentSkill);
        }
    }






}


